<template>
  <view class="container">
    <!-- 标题区域 -->
    <view class="header">
      <text class="title">铅封溯源信息</text>
      <text class="subtitle">编号：{{ snCode }}</text>
    </view>
    <!-- 时间线 -->
    <view class="timeline">
      <view class="timeline-line"></view>
      <!-- 时间节点列表 -->
      <view class="timeline-nodes">
        <!-- 当数据为空时显示提示 -->
        <view v-if="timelineData.length === 0" class="no-data">
          <text>暂无数据</text>
        </view>
        <view
            v-for="(item, index) in timelineData"
            :key="index"
            class="timeline-item"
        >
          <view class="node-dot"></view>
          <view class="node-content">
            <view class="node-details">
              <text class="detail-text">操作人员： {{ item.opUser }}</text>
              <!-- 确保调用 getStatusLabel 函数 -->
              <text class="detail-text">
                <span>操作状态：</span>
                <view
                    class="status-tag"
                    :style="statusOptions[item.opStatus]?.style"
                >
                  {{ getListStatusLabel(item.opStatus) }}
                </view>
              </text>
              <text class="detail-text">操作备注： {{ item.descript }}</text>
              <text class="detail-text">关联编号：
                <block v-for="(snCode, nIndex) in item.snCode" :key="nIndex">
                  <text class="link-text" @tap="fetchSealnoDetail(snCode)">{{ snCode }}</text>
                  <text v-if="nIndex < item.snCode.length - 1">,</text>
                </block>
              </text>
            </view>
          </view>
        </view>
      </view>
    </view>
    <!-- 加载中提示 -->
    <view v-if="isLoading" class="loading">
      <text>加载中...</text>
    </view>
    <!-- 已到底提示 -->
    <view v-if="isEnd" class="end">
      <text>已经到底了</text>
    </view>

    <!-- 详情弹窗 -->
    <view class="popup-mask" v-if="showDetailPopup">
      <view class="popup-content">
        <view class="popup-header">
          <text class="popup-code">{{ detailData?.snCode }}</text>
          <text @click="closeDetail" class="popup-close-x">×</text>
        </view>
        <view v-if="detailLoading">
          <text>加载中...</text>
        </view>
        <view v-else-if="detailData">
          <view class="popup-row">
            <text class="popup-label">入库批次</text>
            <text class="popup-value">{{ detailData.inDate }}</text>
          </view>
          <view class="popup-row">
            <text class="popup-label">使用对象</text>
            <text class="popup-value">{{ detailData.target }}</text>
          </view>
          <view class="popup-row">
            <text class="popup-label">校验码</text>
            <text class="popup-value">{{ detailData.checkCode }}</text>
          </view>
          <view class="popup-row">
            <text class="popup-label">厂家</text>
            <text class="popup-value">{{ detailData.brand }}</text>
          </view>
          <view class="popup-row">
            <text class="popup-label">是否外部铅封</text>
            <text class="popup-value">
              {{ getIsOutLabel(detailData.isOut) }}
            </text>
          </view>
          <view class="popup-row">
            <text class="popup-label">状态</text>
            <view
                class="popup-value"
                :style="detailStatusOptions[detailData.status]?.style"
            >
              {{ getDetailStatusLabel(detailData.status) }}
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
import {getCurrentInstance, onBeforeMount, onMounted, ref} from 'vue';
import {findAllTblSealnoOperate} from "@/api/function/sealnoOperate/sealnoOperate";
import {findSealnoDetailByCode} from "@/api/function/sealnoStock/sealnoStock";

const { proxy } = getCurrentInstance()!;

// 定义时间线数据项的类型
interface TimelineItem {
  date: string;
  time: string;
  opUser: string;
  descript: string;
  snCode: string[];
  isError: boolean;
  errorReason?: string;
}

// 存储时间线数据
const timelineData = ref<TimelineItem[]>([]);
// 标记是否正在加载数据
const isLoading = ref(false);
// 标记是否已经加载完所有数据
const isEnd = ref(false);
// 当前页码，初始为 1
const currentPage = ref(1);
// 每页加载的数据数量
const pageSize = 10;
// 存储铅封编号
const snCode = ref('');

// 控制详情弹窗的显示隐藏
const showDetailPopup = ref(false);
// 存储铅封详情数据
const detailData = ref<any>(null);
// 标记是否正在加载详情数据
const detailLoading = ref(false);

const isOutOptions = {
  IN: {text: '内部', style: {}},
  OUT: {text: '外部', style: {}}
};

// 列表页使用的状态选项
const statusOptions = {
  BUY_STORE: {text: '验收入库', style: {color: '#52c41a'}}, // 绿色表示正常入库
  TAG: {text: '施打', style: {color: '#1890ff'}}, // 蓝色表示操作中
  UNTAG: {text: '拆封', style: {color: '#faad14'}}, // 黄色表示有操作记录
  DESTORY: {text: '销毁', style: {color: '#888888'}} // 灰色表示已结束
};

// 详情页使用的状态选项
const detailStatusOptions = {
  ACTIVED: {text: '已入库', style: {color: '#52c41a'}},
  LOCKED: {text: '锁定', style: {color: '#faad14'}},
  USING: {text: '已使用', style: {color: '#1890ff'}},
  UERSED: {text: '已作废', style: {color: '#bfbfbf'}},
  DESTROYED: {text: '已销毁', style: {color: '#888888'}},
  ERROR: {text: '异常', style: {color: '#ff4d4f'}}
};

const getIsOutLabel = (value: string) => {
  const option = isOutOptions[value];
  return option? option.text : '未知';
};

// 列表页的 getStatusLabel 方法
const getListStatusLabel = (value: string) => {
  const option = statusOptions[value];
  return option ? option.text : '未知状态';
};

// 详情页的 getStatusLabel 方法
const getDetailStatusLabel = (value: string) => {
  const option = detailStatusOptions[value];
  return option ? option.text : '未知状态';
};

const getStatusClass = (value: string) => {
  return value === 'ACTIVED' ? 'status-normal' : 'status-error';
};

// 修改 getStatusLabel 函数，支持传入不同的状态选项数组
const getStatusLabel = (value: string) => {
  const option = detailStatusOptions[value];
  return option ? option.text : '';
};

const closeDetail = () => {
  showDetailPopup.value = false;
  uni.redirectTo({
    url: '/pages/index'
  });
};

const fetchTimelineData = async (page: number) => {
  if (isLoading.value) return;
  isLoading.value = true;
  try {
    const res = await findAllTblSealnoOperate(page, pageSize, snCode.value);
    if (res.code === 200) {
      const mappedData = res.rows.map((sealnoOperate: any) => {
        const createTime = sealnoOperate.createTime || `${sealnoOperate.inDate}-01-01 00:00:00`;
        const [date, time] = createTime.split(' ');
        return {
          date,
          time,
          opUser: sealnoOperate.opUser,
          opStatus: sealnoOperate.opStatus,
          descript: sealnoOperate.opStatusDescript,
          snCode: sealnoOperate.snCode?.split(',') || []
        };
      });

      if (page === 1) {
        timelineData.value = mappedData;
      } else {
        timelineData.value = timelineData.value.concat(mappedData);
      }

      isEnd.value = timelineData.value.length > 0 && mappedData.length < pageSize;
      if (mappedData.length >= pageSize) {
        currentPage.value = page + 1;
      }
    }
  } catch (error) {
    console.error('Failed to fetch timeline data:', error);
  } finally {
    isLoading.value = false;
  }
};

const fetchSealnoDetail = async (code: string) => {
  showDetailPopup.value = true;
  detailLoading.value = true;
  try {
    const res = await findSealnoDetailByCode(code);
    if (res.code === 200) {
      detailData.value = res.data;
    }
  } catch (error) {
    console.error('Failed to fetch seal detail:', error);
  } finally {
    detailLoading.value = false;
  }
};

onBeforeMount(() => {
  const query = proxy?.$route.query;
  if (query && query.snCode) {
    snCode.value = query.snCode as string;
  }
});

onMounted(() => {
  fetchTimelineData(1);
});

// 点击加载更多记录
const onScrollToLower = () => {
  if (!isEnd.value) {
    // 加载下一页数据
    fetchTimelineData(currentPage.value);
  }
};
const onScrollToUpper = () => {
  if (currentPage.value > 1) {
    currentPage.value--;
    fetchTimelineData(currentPage.value);
  }
};
</script>

<style>
page {
  height: 100%;
  background-color: #f5f5f5;
}

.container {
  padding: 30rpx;
  min-height: 100%;
}

.header {
  margin-bottom: 40rpx;
}

.title {
  font-size: 36px;
  font-weight: bold;
  color: #333;
  display: block; /* 确保独占一行 */
  width: 100%; /* 占满整行 */
}

.subtitle {
  font-size: 14px;
  color: #999;
  margin-top: 10rpx;
  display: block; /* 确保独占一行 */
  width: 100%; /* 占满整行 */
}

.timeline {
  position: relative;
}

.timeline-line {
  position: absolute;
  left: 30rpx;
  top: 0;
  height: 100%;
  width: 2px;
  background-color: #e5e5e5;
}

.timeline-nodes {
  margin-bottom: 30rpx;
}

.timeline-item {
  position: relative;
  padding-left: 80rpx;
  margin-bottom: 40rpx;
}

.node-dot {
  position: absolute;
  left: 16rpx;
  top: 16rpx;
  width: 28rpx;
  height: 28rpx;
  background-color: #999;
  border-radius: 50%;
  border: 8rpx solid #fff;
}

.node-content {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
}

.node-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20rpx;
}

.node-time {
  font-size: 14px;
  color: #999;
  display: block;
}

.node-title {
  font-size: 16px;
  color: #333;
  font-weight: 500;
  margin-top: 10rpx;
  display: block;
}

.error-text {
  color: #fa5151;
}

.node-details {
  font-size: 14px;
  color: #666;
}

.detail-text {
  display: flex;
  justify-content: space-between;
  align-items: center;
  line-height: 40rpx;
}

.link-text {
  color: #1989fa;
}

/* 暂无数据提示样式 */
.no-data {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 400rpx;
  color: #999999;
  font-size: 28rpx;
}

/* 加载中提示样式 */
.loading {
  text-align: center;
  color: #999;
  padding: 20rpx 0;
}

/* 已到底提示样式 */
.end {
  text-align: center;
  color: #999;
  padding: 20rpx 0;
}

.popup-mask {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
}

.popup-content {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  width: 80%;
  max-height: 80%;
  overflow-y: auto;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.popup-code {
  font-size: 16px;
  color: #333;
  font-weight: 500;
  font-weight: bold; /* 添加这行代码让字体加粗 */
}

.popup-close-x {
  font-size: 24px;
  color: #999;
  cursor: pointer;
}

.popup-row {
  display: flex;
  justify-content: space-between; /* 让子元素两端对齐 */
  align-items: center;
  margin-bottom: 10px;
}

.popup-label {
  text-align: left; /* 属性名左对齐 */
  color: #666;
  width: 40%; /* 控制属性名宽度 */
}

.popup-value {
  text-align: right;
  color: #333;
  width: 60%;
  padding: 0 4px !important;
}

.status-tag {
  padding: 2px 8px;
  border-radius: 8px;
  font-size: 14px;
  text-align: center;
  white-space: nowrap; /* 防止换行 */
  transition: background-color 0.3s ease;
  display: inline-block; /* 添加这行，让状态标签和文字在同一行 */
}

.status-normal {
  color: #28a745;
  background-color: rgba(40, 167, 69, 0.2);
}

.status-error {
  color: #dc3545;
  background-color: rgba(220, 53, 69, 0.2);
}
</style>
